<template>
  <!-- 社保公积金台账详情页 -->
  <div id="socialSecurityAccountDetails" class="blackFont">
    <div class="detailsName">
      <span>{{ routeData.subName }}</span>
      <span>{{ `${routeData.yearNumber}年${routeData.monthNumber}月` }}</span>
      <span>{{
        routeData.ledgerName ? routeData.ledgerName : routeData.standingBookName
      }}</span>
    </div>
    <div class="pageHead">
      <el-form ref="listQuery" :model="listQuery" class="listQuery">
        <el-form-item>
          <MultipleDepartments
            ref="departmentsSelect"
            :subId="routeData.subId"
          />
        </el-form-item>
        <el-form-item>
          <el-input placeholder="人员、工号" v-model="listQuery.keyWord" />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :loading="isConfirmLoading"
            @click="handleSearch"
            >搜索</el-button
          >
          <MoreSearchPop
            :visible.sync="isShowMoreSearch"
            ref="moreSearch"
            :formProps="[
              { label: '岗位', prop: 'postName' },
              { label: '员工类型', prop: 'registerType' },
            ]"
          />
        </el-form-item>
        <el-form-item class="btnList">
          <el-button type="primary" @click="handleResetLedgerList"
            >重新计算</el-button
          >
          <el-button type="primary" @click="handleIntroduce"
            >引入人员</el-button
          >
          <el-dropdown @command="handleMoreBtn" style="margin: 0">
            <el-button type="primary" class="moreBtn">更多</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="delete">删除</el-dropdown-item>
              <!-- <el-dropdown-item command="import">导入</el-dropdown-item> -->
              <el-dropdown-item command="export">导出</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-form-item>
      </el-form>
    </div>
    <div class="tableStatistics">
      <div class="leftBox">
        <span>参保人数：{{ summary.insuredTotalCount }}人</span>
        <span>未参保人数：{{ summary.uninsuredTotalCount }}人</span>
        <span>合计：{{ summary.userTotalCount }}人</span>
      </div>
      <div class="rightBox">
        <span
          >个人社保：<span class="redColorFont">{{
            summary.personalSSTotalAmount
          }}</span></span
        >
        <span
          >公司社保：<span class="redColorFont">{{
            summary.companySSTotalAmount
          }}</span></span
        >
        <span
          >个人公积金：<span class="redColorFont">{{
            summary.personalAFTotalAmount
          }}</span></span
        >
        <span
          >公司公积金：<span class="redColorFont">{{
            summary.companyAFTotalAmount
          }}</span></span
        >
        <span
          >合计：<span class="redColorFont">{{
            summary.summaryAmount
          }}</span></span
        >
      </div>
    </div>
    <div class="pageMain">
      <div class="tableContent">
        <el-table
          :data="pageData.items"
          style="width: 100%"
          height="100%"
          border
          v-loading="tableLoading"
          size="medium"
          @selection-change="handleSelectChange"
        >
          <el-table-column align="left" type="selection" />
          <el-table-column align="left" prop="realName" label="姓名" />
          <el-table-column align="left" prop="jobNo" label="工号" />
          <el-table-column align="left" prop="deptName" label="部门" />
          <el-table-column align="left" prop="postName" label="岗位" />
          <el-table-column align="left" prop="insuredCity" label="参保城市" />
          <el-table-column
            align="right"
            prop="ssTotalAmount"
            label="社保合计"
          />
          <el-table-column
            align="right"
            prop="afTotalAmount"
            label="公积金合计"
            width="120"
          />
          <el-table-column label="养老">
            <el-table-column align="right" prop="personalYL" label="个人养老" />
            <el-table-column align="right" prop="companyYL" label="公司养老" />
          </el-table-column>
          <el-table-column label="医疗">
            <el-table-column
              align="right"
              prop="personalMedical"
              label="个人医疗"
            />
            <el-table-column
              align="right"
              prop="companyMedical"
              label="公司医疗"
            />
          </el-table-column>
          <el-table-column label="失业">
            <el-table-column align="right" prop="personalSY" label="个人失业" />
            <el-table-column align="right" prop="companySY" label="公司失业" />
          </el-table-column>
          <el-table-column label="工伤">
            <el-table-column align="right" prop="personalGS" label="个人工伤" />
            <el-table-column align="right" prop="companyGS" label="公司工伤" />
          </el-table-column>
          <el-table-column label="公积金">
            <el-table-column
              align="right"
              prop="personalReservedFunds"
              label="个人公积金"
              width="100"
            />
            <el-table-column
              align="right"
              prop="companyReservedFunds"
              label="公司公积金"
              width="100"
            />
          </el-table-column>
          <el-table-column label="操作" width="150px" align="center">
            <template slot-scope="scope">
              <el-button type="text" @click="handleToSee(scope.row)"
                >查看</el-button
              >
              <el-button
                type="text"
                @click="handleDelete(false, scope.row.ledgerItemId)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination
        :small="true"
        background
        @size-change="(value) => handleSearchChange(value, 'pageSize')"
        @current-change="(value) => handleSearchChange(value, 'pageIndex')"
        :current-page="listQuery.PageIndex"
        :page-sizes="[10, 20, 50]"
        :page-size="listQuery.PageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        class="pagingChild"
      ></el-pagination>
    </div>
    <IntroductionPersonnel
      :visible.sync="isShowIntroduction"
      :subId="routeData.subId"
      :searchDate="[routeData.yearNumber, routeData.monthNumber]"
      @getUserList="handlegetUserList"
    />
    <InsuredDetailsDialog
      :activeData="activeData"
      :pageStatus="1"
      :visible.sync="isShowDetail"
      :isAccount="true"
    />
  </div>
</template>
<script>
import MoreSearchPop from "@/views/personnelRegulate/rewardManagement/components/MoreSearchPop.vue";
import MultipleDepartments from "@/views/personnelRegulate/rewardManagement/components/MultipleDepartments.vue";
import IntroductionPersonnel from "./components/IntroductionPersonnel.vue";
import InsuredDetailsDialog from "./components/InsuredDetailsDialog.vue";
import { math } from "@/util/math.js";
export default {
  name: "socialSecurityAccountDetails",
  components: {
    MoreSearchPop, // 更多查询条件
    IntroductionPersonnel, // 引入人员弹窗
    MultipleDepartments, // 部门多选下拉列表
    InsuredDetailsDialog, // 查询
  },
  data() {
    return {
      date: "",
      listQuery: {
        subId: "",
        keyWord: "",
        ledgerId: 0,
        pageIndex: 1,
        pageSize: 10,
        yearNumber: 0,
        monthNumber: 0,
        deptIdList: [],
      },
      isConfirmLoading: false,
      total: 0,
      tableLoading: false,
      isCreate: true, // 当前是新建还是编辑
      isShowEdit: false, // 控制编辑台账弹窗显示
      isShowMoreSearch: false, // 控制更多查询条件显示
      isShowIntroduction: false, // 控制引入人员弹窗显示
      pageData: {
        //从接口获取的当前台账详情数据
        items: [],
        ssafSummaryModel: {
          ledgerId: 0,
          insuredTotalCount: 0,
          uninsuredTotalCount: 0,
          userTotalCount: 0,
          personalSSTotalAmount: 0,
          companySSTotalAmount: 0,
          personalAFTotalAmount: 0,
          companyAFTotalAmount: 0,
          summaryAmount: 0,
        },
        totalCount: 0,
      },
      isShowDetail: false,
      activeData: {},
      batchList: [],
    };
  },
  computed: {
    routeData() {
      const result = this.$store.state.reward.accountRouterData;
      return result;
    },
    summary() {
      return this.pageData.ssafSummaryModel;
    },
  },
  methods: {
    searchDataList() {
      this.tableLoading = true;
      this.listQuery.subId = this.routeData.subId;
      this.listQuery.ledgerId = this.routeData.ledgerId;
      this.listQuery.monthNumber = this.routeData.monthNumber;
      this.listQuery.yearNumber = this.routeData.yearNumber;

      // this.listQuery.summaryDto.ledgerId = this.routeData.id;
      this.$api.socialSecurity
        .GetLedgerDetailList(this.listQuery)
        .then((res) => {
          if (!res.data.data) {
            return this.$message.warning(
              res.data.message?.length ? res.data.message : "暂无数据"
            );
          }
          if (!res.data.data.ssafSummaryModel) {
            // ssafSummaryModel为空，附初始值
            res.data.data.ssafSummaryModel = this.pageData.ssafSummaryModel;
          }
          this.pageData = res.data.data;
          // this.formatTableData(this.pageData.items);
          // this.pageData.items = [...this.pageData.items,1,1,1,1,1,1,1,1] 
          this.$set(
            this.pageData,
            "items",
            this.formatTableData(this.pageData.items)
          );
          this.total = this.pageData.totalCount;
        })
        .finally(() => {
          this.tableLoading = false;
        });
    },

    formatTableData(listData) {
      return listData.map((e) => {
        for (const key in e) {
          if (
            [
              "ssTotalAmount",
              "afTotalAmount",
              "personalYL",
              "companyYL",
              "personalMedical",
              "companyMedical",
              "personalSY",
              "companySY",
              "personalGS",
              "companyGS",
              "personalReservedFunds",
              "companyReservedFunds",
            ].includes(key)
          ) {
            e[key] = math.toFixed(e[key]);
          }
        }
        return e;
      });
    },
    createAccount(data) {
      // console.log("新增台账数据", data);
      data.operateType = this.routeData.ledgerId > 0 ? 2 : 1;
      data.ledgerId = this.routeData.ledgerId;
      if (this.routeData.id) {
        // 是编辑
      }
      this.$api.socialSecurity.GenerateLedgerList(data).then((res) => {
        // console.log(res);
        if (res.data.status == 200) {
          let accountData = this.$store.state.reward.accountRouterData;
          accountData.ledgerId = res.data.data.ssafSummaryModel.ledgerId;
          this.$store.commit("SET_ACCOUNT_ROUTER_DATA", accountData);
          this.pageData = res.data.data;
          this.$set(
            this.pageData,
            "items",
            this.formatTableData(this.pageData.items)
          );
          this.total = this.pageData.totalCount;
          this.$message.success(`操作成功`);
          this.isShowIntroduction = false;
        }
      });
    },
    editAccount(data) {
      console.log(data);
    },
    deleteAccountDetail(list) {
      this.$api.socialSecurity.DeleteLedgerDetail(list).then((res) => {
        // console.log(res);
        if (res.data.status == 200) {
          this.$message.success(res.data.message);
          this.searchDataList();
        }
      });
    },
    handleSelectChange(selection) {
      this.batchList = selection;
    },
    handleSearch() {
      const { registerType, postName } = this.$refs.moreSearch.getFormData();
      // 从部门多选组件获取部门id数组
      this.listQuery.deptIdList = this.$refs.departmentsSelect.getDepartments();
      console.log(registerType, postName);
      this.listQuery.postName = postName;
      this.listQuery.registerType = registerType;
      this.isShowMoreSearch = false;
      this.listQuery.pageIndex = 1;
      this.searchDataList();
    },
    handleDelete(isBatch, id) {
      if (isBatch && this.batchList.length == 0) {
        return this.$message.warning("请勾选需要批量删除的数据");
      }
      this.$confirm("此操作将永久删除文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          if (!isBatch) {
            this.deleteAccountDetail([id]);
          } else {
            this.deleteAccountDetail(this.batchList.map((e) => e.ledgerItemId));
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleExport() {
      this.$api.socialSecurity
        .ExportLedgerDetailList({ ledgerId: this.routeData.ledgerId })
        .then((res) => {
          console.log(res);
          if (res.data.status == 200) {
            const a = document.createElement("a");
            a.setAttribute("href", res.data.data);
            a.setAttribute("download", "");
            a.click();
          } else {
            this.$message.warning(res.data.message);
          }
        });
    },
    handleToSee(data) {
      // 打开当前条的社保详情弹窗
      this.activeData = data;
      this.activeData.subId = this.routeData.subId;
      this.isShowDetail = true;
    },
    handleEdit(isCreate) {
      this.isShowEdit = true;
      this.isCreate = isCreate;
    },

    /**
     * @description 引入人员
     */
    handleIntroduce() {
      this.isShowIntroduction = true;
    },

    /**
     * @description 重新计算
     */
    handleResetLedgerList() {
      this.listQuery.subId = this.routeData.subId;
      this.listQuery.ledgerId = this.routeData.ledgerId;
      this.listQuery.monthNumber = parseInt(this.routeData.monthNumber);
      this.listQuery.yearNumber = parseInt(this.routeData.yearNumber);
      console.log(this.listQuery);
      const { yearNumber, monthNumber, ledgerId, companyId, subId, pageSize } =
        this.listQuery;
      const data = {
        yearNumber,
        monthNumber,
        ledgerId,
        companyId,
        subId,
        pageSize,
      };

      this.tableLoading = true;
      this.$api.socialSecurity
        .ResetLedgerList(data)
        .then((res) => {
          if (!res.data.data) {
            return this.$message.warning(
              res.data.message?.length ? res.data.message : "暂无数据"
            );
          }
          if (!res.data.data.ssafSummaryModel) {
            // ssafSummaryModel为空，附初始值
            res.data.data.ssafSummaryModel = this.pageData.ssafSummaryModel;
          }
          this.pageData = res.data.data;
          this.$set(
            this.pageData,
            "items",
            this.formatTableData(this.pageData.items)
          );
          this.total = this.pageData.totalCount;
        })
        .finally(() => {
          this.tableLoading = false;
        });
    },
    handlegetUserList(userDataList) {
      let data = {
        ...this.routeData,
        userDataList,
      };
      delete data.subName;
      data.yearNumber = parseInt(data.yearNumber);
      data.monthNumber = parseInt(data.monthNumber);
      data.pageSize = this.listQuery.pageSize;
      this.createAccount(data);
    },
    handleMoreBtn(command) {
      switch (command) {
        case "delete":
          this.handleDelete(true);
          break;
        case "import":
          break;
        case "export":
          this.handleExport();
          break;
      }
    },
    handleSearchChange(value, prop) {
      this.listQuery[prop] = value;
      this.searchDataList();
    },
  },
  activated() {
    // 如果 route.query.fromPage == accountList 执行查询方法
    // console.log(this.$route.query.fromPage);
    if (this.$route.query.fromPage == "accountList") {
      this.searchDataList();
    }
  },
  beforeDestroy() {
    console.log("详情页销毁前执行");
    // 销毁localStorage中储存的之前页面的传参
    localStorage.removeItem("accountRouterData");
  },
};
</script>
<style lang="less" scoped>
@import url("../less/common.less");
#socialSecurityAccountDetails {
  min-width: 815px;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  &>* {
    width: 100%;
  }
  .tableStatistics,
  .detailsName {
    min-height: 40px;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #dcdfe6;
    margin-bottom: 5px;
    span {
      margin-right: 20px;
      &:first-child {
        font-weight: 600;
        font-size: 17px;
      }
    }
  }
  .tableStatistics {
    width: 100%;
    flex: 1;
    font-size: 14px;
    font-weight: normal;
    display: flex;
    align-content: center;
    justify-content: space-between;
    border: none;
    .leftBox,
    .rightBox {
      span {
        margin-right: 25px;
        &:last-child {
          margin-right: 0;
        }
        &:first-child {
          font-weight: normal;
          font-size: 14px;
        }
      }
    }
  }
  .pageMain {
    position: relative;
    height: calc(100% - 125px);
    margin-top: 0;
  }
  .tableContent {
    position: relative;
    padding: 0;
    // height: calc(100% - 28px);
  }
  .pagingChild {
    float: right;
    margin-right: 10px;
    margin-top: 5px;
    .el-pagination__total {
      line-height: 28px;
    }
  }
  .listQuery {
    .el-form-item {
      float: left;
      width: 150px;
      margin-right: 15px;
      .el-input {
        width: 100%;
      }
    }
    .btnList {
      width: 230px;
      float: right;
      text-align: right;
      margin-right: 0;
      // :deep(.el-form-item__content {
      //   & > * {
      //     margin-left: 10px;
      //   }
      // }
      // .moreBtn {
      // }
    }
  }
}
</style>